import Store from '../store'

// 文件下载
export function excelDownload(res, fileName) {
  if (!res) {
    return
  }
  if (!fileName && res.config.url && res.config.url.indexOf('fileName=') > -1) {
    const Name = res.config.url.split('?')[1]
    fileName = new URLSearchParams(Name).get('fileName')
  }
  if (res.headers && res.headers['content-type'].indexOf('application/json') < 0) {
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    // let fileName = res.headers["content-disposition"].split("filename=");
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
  } else {
    const enc = new TextDecoder('utf-8')
    const json = res.data
    json.arrayBuffer().then(buffer => {
      const data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {}
      alert(data.message)
    })
  }
}

export function zipDownload(res, fileName) {
  if (!res) {
    return
  }
  if (!fileName && res.headers && res.headers['content-disposition'] && res.headers['content-disposition'].indexOf('filename=') > -1) {
    fileName = res.headers['content-disposition'].split('filename=')[1]
  }
  if (res.headers && res.headers['content-type'].indexOf('application/zip') < 0) {
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url

    // let fileName = res.headers["content-disposition"].split("filename=");
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
  } else {
    const enc = new TextDecoder('utf-8')
    const json = res.data
    json.arrayBuffer().then(buffer => {
      const data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {}
      alert(data.message)
    })
  }
}

export const parseSelectData = ({
  data,
  valueKey,
  labelKey,
  isUnlimited = true,
  defaultValue = null,
  defaultUnlimited = '不限'
}) => {
  // 处理数据，给各选项添加 ‘不限’选项
  const arr = isUnlimited ? [{ value: defaultValue, label: defaultUnlimited }] : []
  if (data && data.length) {
    data.forEach(item => {
      arr.push({
        value: item[valueKey],
        label: item[labelKey]
      })
    })
  }
  return arr
}

// 状态转换
export const parseStatusSelectData = ({
  data,
  valueKey,
  labelKey,
  filterKey,
  filterValue,
  isUnlimited = true,
  defaultValue = null,
  defaultUnlimited = '不限'
}) => {
  // 处理数据，给各选项添加 ‘不限’选项
  const arr = isUnlimited ? [{ value: defaultValue, label: defaultUnlimited }] : []
  if (data && data.length) {
    data.forEach(item => {
      if (item[filterKey] === filterValue) {
        arr.push({
          value: item[valueKey],
          label: item[labelKey]
        })
      }
    })
  }
  return arr
}

// 通用查找value值对应显示string方法
export const searchStr = (value, valueKey, strKey, targetArr) => {
  let temp = ''
  if (targetArr && targetArr.length) {
    targetArr.forEach(item => {
      if (item[valueKey] === value) {
        temp = item[strKey]
      }
    })
  }
  if (temp === '不限') {
    return ''
  }
  return temp
}

// 获取当前时间N天之后的时间
export function getPastDay(n) {
  let dd = new Date()
  let timestamp = dd.getTime()
  timestamp = timestamp + n * 24 * 3600 * 1000
  dd = new Date(timestamp)
  const y = dd.getFullYear()
  const m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1)// 获取当前月份的日期，不足10补0
  const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()// 获取当前几号，不足10补0
  return y + '-' + m + '-' + d
}

// 时间格式化 --date需要是字符串 yyyy-MM-dd HH:mm:ss.ms
export function dateFormat(date) {
  if (!date) {
    return ''
  }
  const dd = new Date(date)
  if (dd.getFullYear()) {
    var Y = dd.getFullYear() + '-'
    var M = (dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1) + '-'
    var D = (dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()) + ' '
    var h = (dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()) + ':'
    var m = (dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()) + ':'
    var s = (dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds())
    return Y + M + D + h + m + s
  } else {
    date = date.replace('T', ' ')
    return date.split('.')[0]
  }
}

// 日期格式化 --date需要是字符串 yyyy-MM-dd HH:mm:ss.ms
export function dayFormat(date) {
  if (!date) {
    return ''
  }
  const dd = new Date(date)
  if (dd.getFullYear()) {
    var Y = dd.getFullYear() + '-'
    var M = (dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1) + '-'
    var D = (dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()) + ' '
    return Y + M + D
  } else {
    return date.substring(0, 10)
  }
}

// 获取当前时间
export function getNowTime() {
  const dd = new Date()
  var Y = dd.getFullYear() + '-'
  var M = (dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1) + '-'
  var D = (dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()) + ' '
  var h = (dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()) + ':'
  var m = (dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()) + ':'
  var s = (dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds())
  return Y + M + D + h + m + s
}

// 生成随机数
export function createCode() {
  var num = ''
  for (var i = 0; i < 3; i++) {
    num += Math.floor(Math.random() * 10)
  }
  return (new Date()).getTime() + num
}

// 获取url
const getUrl = function() {
  const arr = window.location.pathname.split('/')
  let url = ''
  const evn = process.env.VUE_APP_ENV.split('/')
  arr.forEach(item => {
    if (item !== '' && item !== evn[1]) {
      url = url + '/' + item
    }
  })
  return url
}

// 验证按钮权限
export function button(name) {
  const url = getUrl()
  const buttonArr = Store.getters.buttonArr
  return buttonArr.includes(url + '/' + name)
}

export function getMenuId() {
  const url = getUrl()
  const menuList = JSON.parse(sessionStorage.getItem('menuList'))
  let menuId = null
  menuList.forEach(item => { if (item.curl === url) menuId = item.menuId })
  return menuId
}

export function setShow(arr) {
  if (arr.length === 0) return []
  arr.forEach(function(item) {
    item.show = button(item.key)
  })
  return arr
}

// 将数据初始化至筛选框的样子
export function setScreen(arr, label) {
  if (arr && arr.length !== 0 && label) {
    return arr.map(item => {
      item = {
        value: label.value === 'item' ? item : item[label.value],
        label: label.label === 'item' ? item : item[label.label]
      }
      return item
    })
  }
  return []
}

// 将数组转换为 , 连接的方式
export function transition(arr) {
  if (arr?.length > 0) {
    let str = ''
    arr.forEach(item => {
      str ? str = str + ',' + item : str = str + item
    })
    return str
  } else {
    return ''
  }
}

/**
 * @param url
 * @param data
 * @returns url get请求url拼接好的
 */
export function setUrl(url, data) {
  const dataList = Object.keys(data)
  dataList.forEach(item => {
    if (data[item] || +data[item] === 0 && data[item] !== null && data[item] !== '' && data[item] !== undefined) {
      if (!url.includes('?')) {
        url = url + '?' + item + '=' + data[item]
      } else {
        url = `${url}&${item}=${data[item]}`
      }
    }
  })
  return url
}

export function setArr(item, arr, type = 0) {
  let a = ''
  if (arr?.length > 0) {
    if (type === 0) {
      arr.forEach(function(it) {
        if (+item === +it.value) {
          a = it.label
        }
      })
    } else {
      arr.forEach(function(it) {
        if (item === it.label) {
          a = it.value
        }
      })
    }
  }
  return a
}
